package top.heliming.youyou.cart.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import top.heliming.youyou.cart.config.JwtProperties;
import top.heliming.youyou.common.utils.CookieUtils;
import top.heliming.youyou.entity.UserInfo;
import top.heliming.youyou.util.JwtUtils;

/**
 * description: //拦截器
 *
 * @author: heliming
 * @date:2019/06/14 下午 9:46
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

  private JwtProperties jwtProperties;

  // 定义一个线程域，存放登录用户
  private static final ThreadLocal<UserInfo> tl = new ThreadLocal<>();

  public LoginInterceptor(JwtProperties jwtProperties) {
    this.jwtProperties = jwtProperties;
  }

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    // 查询token
    String token = CookieUtils.getCookieValue(request, "LY_TOKEN");
    if (StringUtils.isBlank(token)) {
      // 未登录,返回401
      response.setStatus(HttpStatus.UNAUTHORIZED.value());
      return false;
    }
    // 有token，查询用户信息
    try {
      // 解析成功，证明已经登录
      UserInfo user = JwtUtils.getUserInfo( jwtProperties.getPublicKey(),token);
      // 放入线程域
      tl.set(user);
      return true;
    } catch (Exception e){
      // 抛出异常，证明未登录,返回401
      response.setStatus(HttpStatus.UNAUTHORIZED.value());
      return false;
    }

  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    tl.remove();
  }

  public static UserInfo getLoginUser() {
    return tl.get();
  }
}
